package com.fjnu.aspect;

import com.fjnu.annotation.NPECatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Aspect
@Component
public class ExceptionHandlingAspect {

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    // 切入点：匹配所有带有@NPECatch注解的类或方法
    @Pointcut("@within(com.fjnu.annotation.NPECatch) || @annotation(com.fjnu.annotation.NPECatch)")
    public void npeCatchPointcut() {}

    // 统一的异常处理逻辑，适用于类级别和方法级别的@NPECatch注解
    @Around("npeCatchPointcut()")
    public Object handleNpeException(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName();
        String className = joinPoint.getTarget().getClass().getSimpleName();

        try {
            return joinPoint.proceed();
        } catch (Exception e) {
            System.out.println("[" + LocalDateTime.now().format(formatter) + "] " +
                    "Method: " + className + "." + methodName +
                    ", Exception: " + e.getClass().getSimpleName() +
                    ", Message: " + e.getMessage());
            throw e;
        }
    }
}